package com.xbdun.service.bmp.facade;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xbdun.common.api.Client;
import com.xbdun.common.api.XbdUnStringResult;
import com.xbdun.common.enums.UserRolesEnums;
import com.xbdun.common.enums.YesOrNoEnum;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.page.Pager;
import com.xbdun.common.util.CommonUtil;
import com.xbdun.common.validate.ValidateUtil;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgAuditingStatusEnum;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgEnableEnum;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgTypeEnum;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.request.system.SysOrgAuditingRequest;
import com.xbdun.facade.bmp.request.system.SysOrgModifyRequest;
import com.xbdun.facade.bmp.request.system.SysOrgPagerRequest;
import com.xbdun.facade.bmp.request.system.SysOrgRequest;
import com.xbdun.facade.bmp.response.system.SysOrgResponse;
import com.xbdun.facade.bmp.result.system.SysOrgPagerResult;
import com.xbdun.facade.bmp.result.system.SysOrgResult;
import com.xbdun.facade.bmp.service.system.SysOrgFacade;
import com.xbdun.service.bmp.service.system.SysOrgService;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: SysOrgFacadeImpl
 * @Description: 企业信息
 * @author zhanggt 360730440@qq.com
 * @date 2017年3月21日 下午3:15:30
 */
@Component
//@Service(group = DubboConstant.BUSI_PROTAL_GROUP, version = DubboConstant.BUSI_PROTAL_VERSION,retries=DubboConstant.BUSI_PROTAL_RETRY)
@Slf4j
public class SysOrgFacadeImpl implements SysOrgFacade {

	@Autowired
	private SysOrgService sysOrgService;

	/**
	 * @Title: addSysOrg
	 * @Description: 新增企业基本信息
	 * @param request
	 *            请求参数
	 * @throws Exception
	 *             设定文件
	 * @return void 返回类型
	 */
	public XbdUnStringResult addSysOrg(SysOrgRequest request,Client client) {
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 新增企业初始参数,{}", request);
			addSysOrgChecked(request);
			sysOrgService.addSysOrg(request);
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("新增企业信息失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 新增企业结果:{}", result);
		}
		return result;
	}

	/**
	 * @Title: getSysOrgByOrgCode
	 * @Description: 根据企业ID查询企业基本信息
	 * @param id
	 * @return SysOrgResult 返回类型
	 */
	public SysOrgResult getSysOrgByOrgCode(long orgCode) {
		SysOrgResult result = new SysOrgResult();
		try {
			result.setData(sysOrgService.getSysOrgByOrgCode(orgCode));
		} catch (Exception e) {
			result.setBizException(e);
			log.error("获取企业基本信息失败,入参:{},异常:{}", orgCode, e);
		}
		return result;
	}

	/**
	 * @Title: queryPager
	 * @Description: 分页查询
	 * @param requestPager
	 *            请求参数
	 * @return SysOrgPagerResult 返回类型
	 */
	public SysOrgPagerResult queryPager(SysOrgPagerRequest requestPager,Client client) {
		SysOrgPagerResult result = new SysOrgPagerResult();
		try {
			CommonUtil.validateClient(client);
			chekedQueryPager(requestPager);
			Pager<SysOrgResponse> queryPager = sysOrgService.queryPager(requestPager,client);
			if (null == queryPager) {
				throw BizException.DB_LIST_IS_NULL;
			}
			result.setData(queryPager);
		} catch (Exception e) {
			result.setBizException(e);
			log.error("企业分页查询信息失败,入参:{},异常:{}", requestPager, e);
		}
		return result;
	}

	public XbdUnStringResult modifySysOrg(SysOrgModifyRequest request,Client client){
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 修改企业信息入参:" + request);
			if(client.getOrgCode()!=0){
				CommonUtil.validateClient(client);
			}
			chekedModifySysOrg(request,client);
			sysOrgService.modifySysOrg(request,client);
		} catch (Exception e) {
			result.setBizException(e);
			log.error("修改企业基本信息失败,入参:{},异常:{}", request, e);
		} finally {
			log.info("end - 修改企业信息入参{}", result);
		}
		return result;
	}
	
	/**
	* @Title: modifyAgentOrg
	* @Description: 设置代理机构
	* @param orgCode		机构编编号
	* @param yesOrNoEnum	是否为代理机构
	* @return void    返回类型
	 */
	public XbdUnStringResult modifyAgentOrg(long orgCode,int blAgent,Client client){
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 设置机构代理入参:" + orgCode);
			CommonUtil.validateClient(client);
			YesOrNoEnum yesOrNo = YesOrNoEnum.getEnum(blAgent);
			if(null==yesOrNo||YesOrNoEnum.NOMAL.equals(yesOrNo)){
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("设置是否代理机构类型系统未定义【"+blAgent+"】");
			}
			sysOrgService.modifyAgentOrg(orgCode, yesOrNo);
		} catch (Exception e) {
			result.setBizException(e);
			log.error("设置代理机构失败,入参:{},异常:{}", orgCode, e);
		} finally {
			log.info("end - 设置代理机构{}", result);
		}
		return result;
	}

	//检测修改机构信息
	private void chekedModifySysOrg(SysOrgModifyRequest request,Client client)throws BizException{
		if (null == request || request.getId() <= 0){
			throw BizException.PARAM_CHKE_FAIL.newInstance("机构ID不能小于等于零");
		}
		if (null!=request.getAuditingStatus()) {// 审核状态
			if(!SysOrgAuditingStatusEnum.isKey(request.getAuditingStatus())){
				throw BizException.PARAM_CHKE_FAIL.newInstance("审核状态未定义");
			}
			//说明在设置状态
			if(request.getAuditingStatus().intValue()!=1&&client.getRoleId()!=UserRolesEnums.XBDADMINT.getKey()){
				throw BizException.POWER_FAIL.newInstance("修改企业信息，必须为平台管理员才有权限");
			}
		}
		if (null != request.getEnable()){// 停用/启用
			if (!SysOrgEnableEnum.isKey(request.getEnable())) {
				throw BizException.PARAM_CHKE_FAIL.newInstance("查询启用状态不在范围内");
			}else{
				if(SysOrgEnableEnum.ON.getKey()==request.getEnable()&&client.getRoleId()!=UserRolesEnums.XBDADMINT.getKey()){
					throw BizException.POWER_FAIL.newInstance("修改企业信息，必须为平台管理员才有权限");
				}
			}
		}
	}
	// 检测新增企业信息
	private void addSysOrgChecked(SysOrgRequest request)throws BizException {
		if (null == request){
			throw BizException.PARAM_CHKE_FAIL.newInstance("请求对象不能为空");
		}
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isBlank(request.getOrgName())) {
			sb.append("企业名不能为空;");
		}
		if (StringUtils.isBlank(request.getBusiPerson())) {
			sb.append("企业法人不能为空;");
		}
		if (StringUtils.isBlank(request.getAddr())) {
			sb.append("企业地址不能为空;");
		}
		// 判断座机的电话
		if (StringUtils.isBlank(request.getOrgMobile()) && StringUtils.isBlank(request.getOrgLandline())) {
			sb.append("企业座机和电话不能同时为空;");
		} else {
			if (null != request.getOrgMobile()) {
				if (!ValidateUtil.isMobile(request.getOrgMobile())) {
					sb.append("企业电话格式不正确;");
				}
			}
			if (null != request.getOrgLandline()) {
				if (!ValidateUtil.isPhone(request.getOrgLandline())) {
					sb.append("企业座机座机格式;");
				}
			}
		}
		if (!ValidateUtil.isEmail(request.getOrgEmail())) {
			sb.append("企业邮箱格式不正确;");
		}
		if (StringUtils.isBlank(request.getRecordNo())) {
			sb.append("企业备案号不能为空;");
		}
		if (StringUtils.isBlank(request.getRecordImg())) {
			sb.append("企业备案照片不能为空;");
		}
		if(StringUtils.isBlank(request.getUnionid())){
			sb.append("微信小程序UnionId不能为空;");
		}
		if(!ValidateUtil.isIdCard(request.getIdCard())){
			sb.append("身份证号格式不正确;");
		}
		if(StringUtils.isBlank(request.getPwd())){
			sb.append("密码不能为空;");
		}
		if(null==SysOrgTypeEnum.getEnum(request.getType())){
			sb.append("企业类型未定义;");
		}
		if (sb.length() > 0) {
			throw BizException.PARAM_CHKE_FAIL.newInstance("%s", sb.toString());
		}
	}
	
	//查询条件检测
	private void chekedQueryPager(SysOrgPagerRequest requestPager) {
		if (null == requestPager){
			throw BizException.PARAM_CHKE_FAIL.newInstance("请求对象不能为空");
		}
		StringBuilder sb = new StringBuilder();
		if (requestPager.getAuditingStatus() != 0) {
			if (!SysOrgAuditingStatusEnum.isKey(requestPager.getAuditingStatus())){
				sb.append("审核状态参数不合法;");
			}
		}
		if (requestPager.getEnable() != 0) {
			if (!SysOrgEnableEnum.isKey(requestPager.getEnable())){
				sb.append("启用状态参数不合法;");
			}
		}
		if (requestPager.getSelectKey() < 0) {
			sb.append("关键字查询条件不合法;");
		}
		if (sb.length() > 0) {
			throw BizException.PARAM_CHKE_FAIL.newInstance("%s", sb.toString());
		}
	}
	
	public XbdUnStringResult auditingSysOrg(SysOrgAuditingRequest request,Client client){
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 修改企业信息入参:" + request);
			if(client.getOrgCode()!=0){
				CommonUtil.validateClient(client);
			}
			if (null == request || request.getId() <= 0){
				throw BizException.PARAM_CHKE_FAIL.newInstance("机构ID不能小于等于零");
			}
			if (null==SysOrgAuditingStatusEnum.getEnum(request.getAuditingStatus())){
				throw BizException.PARAM_CHKE_FAIL.newInstance("审核状态未定义;");
			}
			if (StringUtils.isBlank(request.getRemarks())){
				throw BizException.PARAM_CHKE_FAIL.newInstance("审核内容不能为空;");
			}
			sysOrgService.auditingSysOrg(request,client);
		} catch (Exception e) {
			result.setBizException(e);
			log.error("修改企业基本信息失败,入参:{},异常:{}", request, e);
		} finally {
			log.info("end - 修改企业信息入参{}", result);
		}
		return result;
	}
}
